import { ConfigEnv, UserConfigExport, defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from "path";
import { pageUrl } from "./src/config";
import zipPack from "vite-plugin-zip-pack";
import cdn from 'vite-plugin-cdn-import'
// import { VitePWA } from 'vite-plugin-pwa'
import mkcert from "vite-plugin-mkcert";
import lanMonitor from "./plugins/lan_monitor.js"
const timeStamp = new Date().getTime();

export default function ({ command, mode }: ConfigEnv): UserConfigExport {
  console.log(mode);
  const env = loadEnv(mode, process.cwd());
  const { VITE_SYSTEM_URL, VITE_THINKLINK_URL, VITE_PAGE, VITE_DIAG_URL, VITE_ORDER_URL, VITE_THINKLINK_CN_URL } = env;
  const outputName = `${VITE_PAGE?.trim() || "dist"}`;

  return {
    base: "./",
    resolve: {
      alias: {
        "@": resolve(__dirname, "src"),
        "/src/main.tsx": (pageUrl as any)[VITE_PAGE?.trim() || "base"]
      },
    },
    server: {
      // https:{},// 是否开启https
      host: "0.0.0.0",
      port: 5173,
      proxy: {
        '/system_api': {
          target: VITE_SYSTEM_URL,
          rewrite: (path) => path.replace(/^\/system_api/, ''),
          changeOrigin: true
        },
        '/thinklink_api': {
          target: VITE_THINKLINK_URL,
          rewrite: (path) => path.replace(/^\/thinklink_api/, ''),
          changeOrigin: true
        },
        '/thinklink_cn_api': {
          target: VITE_THINKLINK_CN_URL,
          rewrite: (path) => path.replace(/^\/thinklink_cn_api/, ''),
          changeOrigin: true
        },
        '/diag_api': {
          target: VITE_DIAG_URL,
          rewrite: (path) => path.replace(/^\/diag_api/, ''),
          changeOrigin: true
        },
        '/order_api': {
          target: VITE_ORDER_URL,
          rewrite: (path) => path.replace(/^\/order_api/, ''),
          changeOrigin: true
        },

      },
    },
    plugins: [react(), zipPack({
      inDir: `dist/package/${outputName}`,
      outDir: 'dist',
      outFileName: `${outputName}.zip`,
    }),
    cdn({
      enableInDevMode: true,
      modules: ['react', 'react-dom', 'axios', 'dayjs', 'antd','react-router-dom'],
    }),
      // VitePWA(
      //   {
      //     registerType: 'autoUpdate', manifest: {
      //       name: '这是个项目名', // 项目名
      //       id: "csdn",
      //       short_name: 'MyApp',
      //       start_url:"http://localhost:5173/report/tire_tread?report_id=62",
      //       description: '一个Vite PWA测试APP',
      //       theme_color: '#DC143C', // 红 // 用于设置工具栏的颜色，并且可以反映在任务切换器中的应用预览中。theme_color 应与文档标头中指定的 meta 主题颜色一致。
      //       background_color: '#FFFF00', // 黄-首次在移动设备上启动应用时，启动画面会使用 background_color 属性。
      //       display: "minimal-ui", // 您可以自定义应用启动时显示的浏览器界面。例如，您可以隐藏地址栏和浏览器界面元素
      //       icons: [		//添加图标，注意路径和图像像素正确，sizes必须和图片的尺寸一致
      //         {
      //           src: 'test.png',
      //           sizes: '500x500', // 大于144
      //           type: 'image/png',
      //         },

      //       ],
      //       screenshots: [ //
      //         {
      //           "src": "test2.png",
      //           "type": "image/png",
      //           "sizes": "540x720",
      //           "form_factor": "narrow"
      //         },
      //         {
      //           "src": "test3.png",
      //           "type": "image/png",
      //           "sizes": "720x540",
      //           "form_factor": "wide"
      //         }]
      //     },
      //     workbox: {
      //       // globPatterns: ['**/*.{js,css,html,ico,png,jpg,svg}'],		// 缓存相关静态资源，这个放开会导致页面html被缓存，谨慎使用
      //     },
      //     devOptions: {
      //       enabled: true
      //     }
      //   },


      // ),
      // mkcert(),
      // lanMonitor() // 文件监控实际没必要
    ],
    build: {
      outDir: `dist/package/${outputName}`,
      rollupOptions: {
        // 打包分类添加时间戳
        output: {
          chunkFileNames: `js/chunk/[name].${process.env.npm_package_version}.${timeStamp}.js`,
          entryFileNames: `js/entry/[name].${process.env.npm_package_version}.${timeStamp}.js`,
          assetFileNames: `[ext]/[name].${process.env.npm_package_version}.${timeStamp}.[ext]`,
          // 超大静态资源拆分
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id
                .toString()
                .split('node_modules/')[1]
                .split('/')[0]
                .toString();
            }
          }
        },
        external: ['react', 'react-dom', 'axios', 'dayjs', 'antd','react-router-dom'],
      }
    }
  };
}

